<template>
  <view class="goods-coupon">
    <!-- #ifdef MP-WEIXIN || MP-ALIPAY-->
    <yy-navbar :auto-back="false" :title="history ? '历史记录' : '套票立减券'" bg-color="#fff" @left-click="backClick"></yy-navbar>
    <!-- #endif-->
    <view v-if="!history" class="goods-coupon__search">
      <view class="goods-coupon__input">
        <u-input v-model="cardCode" class="goods-coupon__uipt" placeholder="输入套票立减券密码绑定" type="text" clearable />
        <view class="goods-coupon__scan" @click.stop="onScan"></view>
      </view>
      <view class="goods-coupon__bind-btn" @click="bindCoupon">绑定</view>
    </view>
    <view :class="listDataLength ? 'goods-coupon__content' : ''">
      <yy-list :list="listData" :loading="listLoading" :finished="fromPage ? true : listFinished" empty-type="coupon">
        <coupon-box v-for="(item, index) in listData" :key="item.couponId" class="goods-coupon__coupon-box" :can-use="getCanUse(item)">
          <view slot="left" class="goods-coupon__coupon-main" @click="toDetail(item)">
            <view class="mlr20">
              <view style="line-height: 1.5">
                <text class="fs30" :class="history ? 'fc-gray' : 'fc-blue-s'">￥</text>
                <text class="goods-coupon__money" :class="history ? 'fc-gray' : 'fc-blue-s'">{{ item.moneyOffConfig.reduceMoney }}</text>
              </view>
              <view class="tc" :class="history ? 'fc-gray' : 'fc-blue-s'">满{{ item.moneyOffConfig.money }}元可用</view>
            </view>
            <view class="goods-coupon__info">
              <view class="onShow fc9">{{ item.couponName }}</view>
              <view class="onShow fc9">{{ item.commodityCouponApplyToMallTypeName }}</view>
              <view class="onShow fc9">有效期： {{ item.sD || '--' }}~{{ item.eD || '--' }}</view>
            </view>
          </view>

          <view slot="right">
            <view v-if="fromPage !== 'sureOrder'">
              <view v-if="history" class="goods-coupon__coupon-status" :class="'goods-coupon__coupon-status--' + getStatus(item)"></view>
              <view v-else-if="item.isFrozen === '1'" class="goods-coupon__coupon-status goods-coupon__coupon-status--freeze"></view>
              <view v-else class="goods-coupon__coupon-btn" @click="onUse">去使用</view>
            </view>

            <view v-else class="goods-coupon__select" @click="onSel(item, index)">
              <view class="goods-coupon__use-bg" :class="item.usable ? 'goods-coupon__use' : 'goods-coupon__no-use'"></view>
              <view v-if="item.usable" class="goods-coupon__ck" :class="item.isSel === '1' ? 'goods-coupon__check' : 'goods-coupon__no-check'"></view>
            </view>
          </view>
        </coupon-box>
      </yy-list>
    </view>

    <view class="goods-coupon__sure-bottom">
      <view v-if="fromPage !== 'sureOrder'" class="goods-coupon__tolook" @click="goHistory">
        <text>{{ history ? '查看可用卡券' : '历史记录' }}</text>
        <u-icon name="arrow-right" color="#333" size="18"></u-icon>
      </view>
      <view v-if="fromPage === 'sureOrder'" class="goods-coupon__sure-btn" @click="select">确定选择</view>
    </view>
  </view>
</template>
<script>
  import CouponBox from '@/pagesOrder/components/CouponBox/index.vue'
  import listMixins from '@/mixins/listMixins'
  import { deDupArray } from '@/utils'
  import { locSelGoodsCoupon, locSelCard } from '@/utils/locStore/data'

  // #ifdef H5
  import { scanQRCode } from '@/utils/sdk'
  import { toast } from '@/utils/message'
  // #endif
  export default {
    name: 'goods-coupon',
    components: { CouponBox },
    mixins: [listMixins],
    data() {
      return {
        cardCode: '',
        fromPage: '',
        flag: false,
        selBox: [],
        fromPath: '',
        isAutoBind: false,
        history: false,
        mallCommodityId: '',
        totalPrice: 0
        // query: {}
      }
    },
    onLoad(option) {
      // #ifdef MP-WEIXIN
      if (option.autoBind) {
        this.autoBindCoupon(option.couponId)
      }
      // #endif
      this.fromPath = this.$tools.getCurrentPage().fromPath
      this.fromPage = option.fromPage || ''
      if (this.fromPage) {
        this.mallCommodityId = option.mallCommodityId || ''
        this.totalPrice = option.totalPrice || ''
      }
      console.log('this.mallCommodityId', this.mallCommodityId)
      this.selBox = locSelGoodsCoupon.get() instanceof Array ? locSelGoodsCoupon.get() : []
    },
    onShow() {
      this.listLoad()
    },

    computed: {
      listDataLength() {
        return this.listData.length > 0
      },
      checkFilmCouponType() {
        return this.fromPage !== 'sureOrder' ? '1' : '2'
      }
    },
    methods: {
      onloadList() {
        const query = {
          ...this.pageInfo,
          ...{
            invalid: this.history ? '2' : '1',
            couponType: '3'
          }
        }
        if (this.mallCommodityId) {
          query.mallCommodityId = this.mallCommodityId
        }

        const getCouponApi = this.fromPage ? uni.$api.coupon.getCouponByMallCommodity : uni.$api.coupon.getCouponList

        return getCouponApi(query).then((res) => {
          if (this.isLoading) {
            // 是下啦刷新 清空
            this.listData = []
          }

          let listData = []
          if (this.fromPage) {
            listData = res
          } else {
            listData = [...this.listData, ...res.list]
          }
          this.listData = deDupArray(listData, 'couponId')
          this.listData.forEach((item) => {
            console.log('this.totalPrice', this.totalPrice, item.mallFullMoney, Number(this.totalPrice) < Number(item.mallFullMoney))
            if (Number(this.totalPrice) < Number(item.mallFullMoney)) {
              item.usable = false
            } else {
              item.usable = true
            }
          })
          this.$nextTick(() => {
            this.onReplace()
          })
          return res
        })
      },
      onPullDownRefresh() {
        this.listRefresh()
      },
      onReachBottom() {
        this.listLoad()
      },
      onScan() {
        console.log('onScan')
        // #ifdef MP-ALIPAY
        uni.scanCode({
          success: (res) => {
            this.bindCode(res.result)
          }
        })
        // #endif
        // #ifdef MP-WEIXIN || MP-TOUTIAO
        uni.authorize({
          scope: 'scope.camera',
          success: () => {
            uni.scanCode({
              success: (res) => {
                this.bindCode(res.result)
              }
            })
          },
          fail: () => {
            //授权失败
            uni.showModal({
              title: '该功能需摄像头授权',
              content: '是否进入权限管理，调整授权？',
              success: (res) => {
                if (res.confirm) {
                  //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                  uni.openSetting({
                    success: (res) => {
                      console.log(res.authSetting)
                    }
                  })
                } else if (res.cancel) {
                  return uni.showToast({
                    title: '已取消！'
                  })
                }
              }
            })
          }
        })

        // #endif
        // #ifdef H5
        scanQRCode().then((res) => {
          this.bindCode(res)
        })
        // #endif
      },
      bindCode(res) {
        uni.$api.card.qrCodeBind({ qrCode: res }).then(() => {
          this.$msg.toast('绑定成功', 'success')
          setTimeout(() => {
            this.listRefresh()
          }, 1500)
        })
      },
      bindCoupon() {
        if (this.cardCode) {
          uni.$api.coupon.bindCoupon({ couponId: this.cardCode }).then(() => {
            this.$msg.toast('绑定成功', 'success')
            setTimeout(() => {
              this.listRefresh()
            }, 1500)
          })
        } else {
          this.$msg.toast('请输入券密码')
        }
      },
      autoBindCoupon(carCode) {
        this.isAutoBind = true
        uni.$api.coupon.bindCoupon({ couponId: carCode }).then(() => {
          this.$msg.toast('绑定成功', 'success')
          setTimeout(() => {
            this.listRefresh()
          }, 1500)
        })
      },
      getCanUse(item) {
        if (this.fromPage !== 'sureOrder') {
          return true
        }
        let isSame = true
        this.selBox.forEach((val) => {
          if (item.douyinOrderNo !== val.douyinOrderNo) {
            isSame = false
          }
        })
        if (isSame) {
          return true
        } else {
          return false
        }
      },
      onSel(item, index) {
        if (!item.usable) {
          return
        }
        if (this.selBox && this.selBox.length > 0) {
          this.selBox = []
        }

        if (item.isSel !== '1') {
          this.listData.forEach((val, idx) => {
            if (val.couponId !== item.couponId) {
              this.$set(this.listData[idx], 'isSel', '0')
            } else {
              this.$set(this.listData[idx], 'isSel', '1')
              this.$nextTick(() => {
                this.selBox.splice(0, 1, val)
              })
            }
          })
        } else {
          this.$set(this.listData[index], 'isSel', '0')
          this.$nextTick(() => {
            this.selBox.splice(0, 1)
          })
        }
      },
      onUse() {
        this.clickUse = true
        this.$tools.navigateTo('/pages/mall/mall', {}, 'switchTab')
      },
      toDetail(item) {
        // #ifndef MP-TOUTIAO
        const query = {
          isGoods: true,
          couponId: item.couponId,
          status: this.getStatus(item),
          isFromSureOrder: this.history ? 'history' : this.fromPage
        }
        this.$tools.navigateTo('/subPages/rightsCodeDetail/index', query)
        // #endif
      },
      onReplace() {
        if (this.selBox && this.selBox.length > 0) {
          const ids = this.selBox.map((item) => item.couponId)
          this.listData.forEach((item, index) => {
            if (ids.includes(item.couponId)) {
              this.$set(this.listData[index], 'isSel', '1')
            }
          })
        }
      },
      backClick() {
        if (this.fromPath === 'pagesOrder/sureOrder/index' || this.fromPath === 'pagesOrder/order/detail' || this.fromPath === 'pagesOrder/goodsPay/index') {
          this.$tools.navigateTo(-1)
        } else if (this.isAutoBind) {
          //自动绑定
          this.$tools.navigateTo('/pages/index/index', {}, 'switchTab')
        } else {
          this.$tools.navigateTo('/pages/mine/index', {}, 'switchTab')
        }
      },
      select() {
        this.clickUse = true
        console.log('this.selBox', this.selBox)
        locSelGoodsCoupon.set(this.selBox)
        locSelCard.remove() //用完券清卡
        this.$tools.navigateTo(-1)
      },
      goHistory() {
        this.history = !this.history
        if (this.history) {
          uni.setNavigationBarTitle({ title: '历史记录' })
        } else {
          uni.setNavigationBarTitle({ title: '套票立减券' })
        }
        this.listRefresh()
      },
      getStatus(item) {
        if (item.isFrozen === '1') {
          return 'freeze'
        } else if (item.isOver === '1') {
          return 'overdue'
        } else if (item.isUse === '1') {
          return 'used'
        } else if (item.isVoid === '1') {
          return 'invalid'
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .goods-coupon {
    overflow-x: hidden;
    overflow-y: auto;
    width: 100%;
    min-height: 100vh;
    background: #f3f5f7;
    padding-bottom: 180rpx;
    .tip {
      background-color: #fdf7d7;
      color: #f8a82d;
      font-size: 24rpx;
      text-align: center;
      line-height: 60rpx;
      box-sizing: border-box;
      border-radius: 16rpx;
      height: 60rpx;
    }
    // 搜索
    &__search {
      background: #fff;
      padding: 19rpx 20rpx 23rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1rpx solid #f3f5f7;
      border-bottom: 1rpx solid #f3f5f7;
    }
    &__input {
      margin-right: 10rpx;
      display: flex;
      width: 560rpx;
      height: 72rpx;
      padding-right: 22rpx;
      padding-left: 30rpx;
      background: #f3f5f7;
      border-radius: 20rpx;
    }
    &__uipt {
      margin-right: 10rpx;
      flex: 1;
    }
    &__scan {
      margin-top: 16rpx;
      width: 40rpx;
      height: 40rpx;
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/icon-scan.png) no-repeat;
      background-size: 100%;
    }
    &__bind-btn {
      width: 130rpx;
      height: 68rpx;
      background: linear-gradient(135deg, #55baff 0%, #34f6af 100%);
      border-radius: 20rpx;
      font-size: 28rpx;
      color: #ffffff;
      line-height: 68rpx;
      text-align: center;
    }
    // 标签
    &__tabs {
      // #ifdef MP-ALIPAY
      display: flex;
      justify-content: center;
      align-items: center;
      // #endif
      width: 100vw;
      height: 80rpx;
      background: #ffffff;
    }
    // 内容
    &__content {
      padding: 20rpx;
    }
    &__coupon-main {
      margin-top: 20rpx;
      line-height: 2;
      box-sizing: border-box;
      margin-left: unset;
      font-size: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    &__coupon-btn {
      margin-top: 50%;
      margin-left: 48%;
      transform: translate(-50%, -50%);
      width: 130rpx;
      height: 56rpx;
      background: linear-gradient(135deg, #ffa633 0%, #f8a82d 100%);
      border-radius: 16rpx;
      font-size: 24rpx;
      color: #ffffff;
      line-height: 56rpx;
      text-align: center;
    }
    &__select {
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
    }
    &__use-bg {
      width: 96rpx;
      height: 96rpx;
    }
    &__use {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/use-active.png) no-repeat;
      background-size: 100%;
    }
    &__no-use {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/use-noActive.png) no-repeat;
      background-size: 100%;
    }
    &__ck {
      position: absolute;
      top: 0;
      right: 0;
      width: 50rpx;
      height: 50rpx;
    }
    &__check {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/check.png) no-repeat;
      background-size: 100%;
    }
    &__no-check {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/no-check.png) no-repeat;
      background-size: 100%;
    }
    &__coupon-status {
      width: 96rpx;
      height: 96rpx;
      // transform: scale(0.5);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    &__coupon-status--used {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-used.png) no-repeat;
      background-size: 100%;
    }
    &__coupon-status--invalid {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-invalid.png) no-repeat;
      background-size: 100%;
    }
    &__coupon-status--overdue {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-overdue.png) no-repeat;
      background-size: 100%;
    }
    &__coupon-status--verification {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-verification.png) no-repeat;
      background-size: 100%;
    }
    &__coupon-status--freeze {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-freeze.png) no-repeat;
      background-size: 100%;
    }
    &__sure-bottom {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 47rpx 0 50rpx 0;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      // height: 197upx;
      background: #fff;
      border-radius: 30rpx 30rpx 0 0;
    }
    &__sure-btn {
      width: 710rpx;
      height: 100rpx;
      background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
      border-radius: 20rpx;
      line-height: 100rpx;
      text-align: center;
      color: #fff;
      font-size: 32rpx;
    }
    &__tolook {
      display: flex;
      align-items: center;
      justify-content: center;
      letter-spacing: 2upx;
      color: #333;
    }
    &__money {
      font-size: 60rpx;
      font-weight: bold;
    }
    &__info {
      flex: 1;
      width: 200rpx;
    }
  }
</style>
